import 'package:dio/dio.dart';
import 'package:extended_image/extended_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:sprintf/sprintf.dart';
import 'package:zupu/global.dart';
import 'DetailPage.dart';

import 'Device.dart';

class ListPage extends StatefulWidget {
  final int index;

  ListPage(this.index);

  @override
  State<ListPage> createState() => _ListPageState();
}

class _ListPageState extends State<ListPage>
    with AutomaticKeepAliveClientMixin {
  List<Device> _list = [];

  @override
  void initState() {
    super.initState();

    EasyLoading.show();

    Future.delayed(const Duration(milliseconds: 1500), () {
      EasyLoading.dismiss();
      List datas = devices;
      if (datas.isNotEmpty) {
        List maps = datas[widget.index];
        for (Map map in maps) {
          _list.add(Device.fromMap(map));
        }
        setState(() {});
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return ListView(
      padding: const EdgeInsets.symmetric(horizontal: 15),
      children: _list.map((e) => _itemWidget(e)).toList(),
    );
  }

  Widget _itemWidget(Device device) {
    double price = double.parse(device.price) / 100.0;

    return InkWell(
      onTap: () {
        Get.to(() => DetailPage(device));
      },
      child: Container(
        height: 100,
        padding: const EdgeInsets.symmetric(horizontal: 15),
        margin: const EdgeInsets.symmetric(vertical: 8),
        decoration: BoxDecoration(
            color: Colors.white, borderRadius: BorderRadius.circular(15)),
        child: Row(
          children: [
            Container(
                decoration: BoxDecoration(
                    border: Border.all(color: Colors.grey.shade200)),
                child: ExtendedImage.network(
                  "http://cdn.wfhero.online/device/${device.pic}.jpg",
                  width: 80,
                  height: 80,
                )),
            const SizedBox(
              width: 15,
            ),
            Expanded(
                child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                    height: 50,
                    child: Text(
                      device.name,
                      maxLines: 2,
                      style: const TextStyle(fontWeight: FontWeight.w600),
                    )),
                Row(
                  children: [
                    Text(
                      sprintf("￥%.2f/天", [price]),
                      style: const TextStyle(color: Colors.red),
                    ),
                  ],
                )
              ],
            ))
          ],
        ),
      ),
    );
  }

  @override
  bool get wantKeepAlive => true;
}
